package net.itxxw.manage_cms_client.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import net.itxxw.framework.domain.cms.CmsPage;
import net.itxxw.framework.domain.cms.CmsSite;
import net.itxxw.framework.domain.cms.response.CmsCode;
import net.itxxw.framework.exception.ExceptionCast;
import net.itxxw.framework.model.response.CommonCode;
import net.itxxw.manage_cms_client.dao.CmsPageRepository;
import net.itxxw.manage_cms_client.dao.CmsSiteRepository;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author：ycpan
 * @date：Created in 2020/12/1 21:03
 * @description：在Service中定义保存页面静态文件到服务器物理路径方法
 * @modified By：
 * @version: $
 */
@Service
public class PageService {
    private static final Logger LOGGER= LoggerFactory.getLogger(PageService.class);

    @Autowired
    CmsPageRepository cmsPageRepository;
    @Autowired
    CmsSiteRepository cmsSiteRepository;
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    //保存html页面到服务器物理路径
    public void savePageToServerPath(String pageId){
          //根据pageId查询cmsPage
        CmsPage cmsPage = this.findCmsPageById(pageId);

        //得到html的文件id，从cmsPage中获取htmlFileId内容
        String htmlFileId = cmsPage.getHtmlFileId();
        if(StringUtils.isEmpty(htmlFileId)){
            ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
        }

        //从gridFS中查询html文件
        InputStream inputStream = this.getFileById(htmlFileId);
        if(inputStream==null){
            ExceptionCast.cast(CmsCode.CMS_GENRATEHTML_HTML_IS_NULL);
            LOGGER.error("getFileById InpuStream is null,htmlFileId:{}",htmlFileId);
        }
        //得到站点的Id
        String siteId = cmsPage.getSiteId();

        //得到站点的信息
        CmsSite cmsSite = this.findCmsSiteById(siteId);
        //得到站点的物理路径
        String sitePhysicalPath = cmsSite.getSitePhysicalPath();
        //得到页面的物理路径
        String pagePath=sitePhysicalPath+cmsPage.getPagePhysicalPath()+cmsPage.getPageName();

//原讲义和视频中使用的是sizePathysicaiPath,但是SizePage中没有这个字段，使用PageCms中的PathysicaiPath代替
        //String pagePath = cmsPage.getPagePhysicalPath() + cmsPage.getPageName();

        FileOutputStream fileOutputStream=null;
        //将html保存到服务器物理路径
        try {
            fileOutputStream=new FileOutputStream(new File(pagePath));
            IOUtils.copy(inputStream,fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionCast.cast(CommonCode.FAIL);
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //根据页面id查询页面信息
    public CmsPage findCmsPageById(String pageId) {
        Optional<CmsPage> optional = cmsPageRepository.findById(pageId);
        if (!optional.isPresent()){
           ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
        }
        CmsPage cmsPage=optional.get();
        return cmsPage;
    }

    //根据文件id从GridFS中查询文件内容
     public InputStream getFileById(String fileId) {
         try {
             //文件对象
             GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
             //打开下载流
             GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
             //定义GridFsResource
             GridFsResource gridFsResource=new GridFsResource(gridFSFile,gridFSDownloadStream);
             return gridFsResource.getInputStream();
         } catch (IOException e) {
             e.printStackTrace();
         }
         return null;
     }

    //根据站点id查询站点信息
     public CmsSite findCmsSiteById(String siteId) {
         Optional<CmsSite> optional = cmsSiteRepository.findById(siteId);
         if(!optional.isPresent()){
            ExceptionCast.cast(CmsCode.CMS_SITE_ISNOTEXIST);
         }
         CmsSite cmsSite = optional.get();
         return  cmsSite;
     }




}
